//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Diagnostics.Contracts;

namespace OpenLS.Spreadsheet.StandardAddIn.Statistics
{
    internal class LogNormalDistribution : ContinuousDistribution
    {
        private readonly double standardDeviation;

        public LogNormalDistribution(double mean, double standardDeviation)
        {
            this.standardDeviation = standardDeviation;
            Mean = mean;
        }


        public double Mean { get; private set; }

        public override double CumulativeProbability(double x)
        {
            Contract.Requires(x > 0);
            double d = (Math.Log(x) - Mean)/ (standardDeviation*Math.Sqrt(2));
            double v1 = Statistician.ErrorFunction(d) - Statistician.ErrorFunction(0);
            double result = 0.5*(1.0 - v1);
            return result;
        }


        protected override SolverParameters GetSolverParameters(double probability)
        {
            const double epsilon = 0.00000000000001;
            return new SolverParameters(epsilon, double.MaxValue, 1);
        }

        public double Probability(double x)
        {
            double a = (Math.Log(x) - Mean) / standardDeviation;
            double sqrt2Pi = Math.Sqrt(2*Math.PI);
            return Math.Exp(-0.5 * a * a) / (x * standardDeviation * sqrt2Pi);
        }
    }
}